from copy import copy
import pandas as pd


def generate_trade_pairs(trade_df) -> list:
    """"""
    trade_df = trade_df.drop_duplicates(subset=["date", "vt_tradeid"])
    #trade_df["reference"] = trade_df["reference"].fillna("manual-manual")
    symbol_long_trades = {}
    symbol_short_trades = {}
    trade_pairs = []

    for n, trade in trade_df.iterrows():
        trade = copy(trade)

        if trade["direction"] == "多":
            same_direction = symbol_long_trades.setdefault(trade["vt_symbol"], [])
            opposite_direction = symbol_short_trades.setdefault(trade["vt_symbol"], [])
        else:
            same_direction = symbol_short_trades.setdefault(trade["vt_symbol"], [])
            opposite_direction = symbol_long_trades.setdefault(trade["vt_symbol"], [])

        while trade["volume"] and opposite_direction:
            open_trade = opposite_direction[0]

            close_volume = min(open_trade["volume"], trade["volume"])
            price_profit = trade["price"] - open_trade["price"] if open_trade["direction"] == "多" else open_trade["price"] - trade["price"]
            reference = trade["reference"]
            gateway_name = trade["gateway_name"]
            if type(reference) is str:
                strategy_name = reference.replace(gateway_name+'_', '')
                spread_name, _ = strategy_name.split('-', 1)
            else:
                reference = "manual"
                strategy_name = "manual"
                spread_name = "manual"
            tp = {
                "vt_symbol": open_trade["vt_symbol"],
                "open_dt": open_trade["datetime"],
                "open_price": open_trade["price"],
                "close_dt": trade["datetime"],
                "close_price": trade["price"],
                "direction": open_trade["direction"],
                "volume": close_volume,
                "price_profit": price_profit,
                "profit_rate": price_profit / open_trade["price"] * 100,
                "gateway_name": trade["gateway_name"],
                "reference": reference,
                "strategy_name": strategy_name,
                "spread_name": spread_name
            }
            trade_pairs.append(tp)

            open_trade["volume"] -= close_volume
            if not open_trade["volume"]:
                opposite_direction.pop(0)

            trade["volume"] -= close_volume

        if trade["volume"]:
            same_direction.append(trade)

    return trade_pairs


def make_day_trade_result():
    trade_pair_df = pd.read_csv("e:\\trade_pairs.csv", encoding="GBK")
    classification = "strategy_name"
    trade_pair_df["close_dt"] = pd.to_datetime(trade_pair_df["close_dt"])
    trade_pair_df["date"] = trade_pair_df["close_dt"].dt.date()
    grouped = trade_pair_df.groupby(by=["date", classification])


if __name__ == '__main__':
    trade_df = pd.read_csv("e:\\trades.csv", encoding="GBK")
    trade_pairs = generate_trade_pairs(trade_df)
    pair_df = pd.DataFrame(trade_pairs)
    pair_df.to_csv("e:\\trade_pairs.csv", encoding="GBK", index=False)
